package battlezone;

import java.awt.event.*;
import java.util.*;

/**
 * The controller
 * The idea here is to monitor whether the keys are pressed or not, and periodically (by default every 50ms) move the tank based on the key depression states.
 * 
 * http://forums.sun.com/thread.jspa?threadID=698156 has some interesting and somewhat helpful information about keyboard input in Java
 */
public class Controller implements KeyListener {
    private Model _model;
    private View _view;
    
    private final Timer _timer = new Timer();
    private final long _reactionTime = Configuration.getInstance().getReactionTime();
    private final Map<Integer, Boolean> _keyDepressionStates = new HashMap<Integer, Boolean>(4);
    
    private static boolean isTrue(Boolean bool) {
        if (bool != null) {
            return bool;
        } else {
            return false;
        }
    }
    
    private TimerTask _pollKeyStatesTask = new TimerTask() {
        public void run() {
            if (isTrue(_keyDepressionStates.get(KeyEvent.VK_LEFT))) {
                _model.pivotMyTankLeft(_reactionTime);
            }

            if (isTrue(_keyDepressionStates.get(KeyEvent.VK_RIGHT))) {
                _model.pivotMyTankRight(_reactionTime);
            }

            if (isTrue(_keyDepressionStates.get(KeyEvent.VK_UP))) {
                _model.moveMyTankForward(_reactionTime);
            }

            if (isTrue(_keyDepressionStates.get(KeyEvent.VK_DOWN))) {
                _model.moveMyTankBackward(_reactionTime);
            }
            
            if (isTrue(_keyDepressionStates.get(KeyEvent.VK_SPACE))) {
                _model.fireMyTank(); //the model will handle limiting the number of projectiles per minute
            }
        }
    };
    
    public Controller() {
        _timer.scheduleAtFixedRate(_pollKeyStatesTask, 0, _reactionTime);
    }

    public void setModel(Model model) {
        if (_model != model) {
            _model = model;
        }
    }

    public void setView(View view) {
        if (_view != view) {
            _view = view;
            _view.setController(this);
        }
    }

    public void keyPressed(KeyEvent e) {
        _keyDepressionStates.put(e.getKeyCode(), true);
    }

    @Override
    public void keyReleased(final KeyEvent e) {
        _keyDepressionStates.put(e.getKeyCode(), false);
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
    }
}
